from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import pandas as pd
import sklearn.svm as svm
from sklearn.model_selection import GridSearchCV 
from sklearn.metrics import precision_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
df = pd.read_csv('C:\\Users\\12948\\Desktop\\垃圾邮件分类\\train.csv', engine='python')

df['encoded_label']=df.Label.map({'spam':0,'ham':1})
print(df.head())


train_data, test_data, train_label, test_label = train_test_split(df.Email,df.encoded_label,test_size=0.7,random_state=0) 



vectorizer = TfidfVectorizer()
x_train_vectorized = vectorizer.fit_transform(train_data)
x_test_vectorized = vectorizer.transform(test_data)


svc = svm.SVC()


param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf'], 'gamma': ['scale', 'auto']}
grid_search = GridSearchCV(svc, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid_search.fit(x_train_vectorized, train_label)


best_svm_gpu = grid_search.best_estimator_
best_svm_gpu.fit(x_train_vectorized, train_label)


predictions = best_svm_gpu.predict(x_test_vectorized)
accuracy = accuracy_score(test_label, predictions)
precision = precision_score(test_label, predictions)
recall = recall_score(test_label, predictions)
f1 =f1_score(test_label, predictions)
print('准确率: ', accuracy)
print('精确度: ', precision)
print('召回率: ', recall)
print('f1: ',f1)
